package com.huanglj.taobaounion.presenter.implement;

import android.util.Log;

import com.huanglj.taobaounion.model.api.Api;
import com.huanglj.taobaounion.model.domain.Categories;
import com.huanglj.taobaounion.presenter.IHomePresenter;
import com.huanglj.taobaounion.utils.LogUtil;
import com.huanglj.taobaounion.utils.RetrofitManager;
import com.huanglj.taobaounion.view.IHomeCallBack;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class HomePresenterImpl implements com.huanglj.taobaounion.presenter.IHomePresenter {

    private static final String TAG = "HomePresenterImpl";

    private Api mApi;
    private List<IHomeCallBack> mCallBackList = new ArrayList<>();

    public HomePresenterImpl(){
        Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
        mApi = retrofit.create(Api.class);
    }


    @Override
    public void getCategories() {
        for (IHomeCallBack iHomeCallBack : mCallBackList) {
            iHomeCallBack.onLoading();
        }
        Call<Categories> task = mApi.getCategories();
        task.enqueue(new Callback<Categories>() {
            @Override
            public void onResponse(Call<Categories> call, Response<Categories> response) {
                if (response.code() == HttpURLConnection.HTTP_OK) {
                    Categories body = response.body();
                    if (body.getData().size()!=0 && body != null) {
                        LogUtil.d(TAG,body.toString());
                        LogUtil.d(TAG,body.getCode()+"");
                        if (mCallBackList != null) {
                            for (IHomeCallBack iHomeCallBack : mCallBackList) {
                                iHomeCallBack.onCategoriesLoadedSuccess(body);
                            }
                        }
                    }else {
                        for (IHomeCallBack iHomeCallBack : mCallBackList) {
                            iHomeCallBack.onEmpty();
                        }
                    }

                }
            }

            @Override
            public void onFailure(Call<Categories> call, Throwable t) {
                LogUtil.e(TAG,"网络通信异常 " + t.toString());
                for (IHomeCallBack iHomeCallBack : mCallBackList) {
                        iHomeCallBack.onError(t.toString());
                }
            }
        });

    }

    @Override
    public void registerViewCallBack(IHomeCallBack callBack) {
        mCallBackList.add(callBack);
    }

    @Override
    public void unregisterViewCallBack(IHomeCallBack callBack) {
        mCallBackList.remove(callBack);
    }
}
